<?php

namespace app\admin\library\traits;

use app\admin\model\UFlowdata;
use Exception;
use think\facade\Config;
use think\facade\Db;
use think\db\exception\PDOException;
use think\exception\ValidateException;

/**
 * 后台控制器trait类
 * 已导入到 @var \app\common\controller\Backend 中
 * 若需修改此类方法：请复制方法至对应控制器后进行重写
 */
trait Backend
{
    /**
     * 排除入库字段
     * @param $params
     * @return mixed
     */
    protected function excludeFields($params)
    {
        if (!is_array($this->preExcludeFields)) {
            $this->preExcludeFields = explode(',', (string)$this->preExcludeFields);
        }

        foreach ($this->preExcludeFields as $field) {
            if (array_key_exists($field, $params)) {
                unset($params[$field]);
            }
        }
        return $params;
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $id  = $this->request->param($this->model->getPk());
        $data  = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 排序
     * @param int $id       排序主键值
     * @param int $targetId 排序位置主键值
     */
    public function sortable(int $id, int $targetId)
    {
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $row    = $this->model->find($id);
        $target = $this->model->find($targetId);

        if (!$row || !$target) {
            $this->error(__('Record not found'));
        }
        if ($row[$this->weighField] == $target[$this->weighField]) {
            $autoSortEqWeight = is_null($this->autoSortEqWeight) ? Config::get('buildadmin.auto_sort_eq_weight') : $this->autoSortEqWeight;
            if (!$autoSortEqWeight) {
                $this->error(__('Invalid collation because the weights of the two targets are equal'));
            }

            // 自动重新整理排序
            $all = $this->model->select();
            foreach ($all as $item) {
                $item[$this->weighField] = $item[$this->model->getPk()];
                $item->save();
            }
            unset($all);
            // 重新获取
            $row    = $this->model->find($id);
            $target = $this->model->find($targetId);
        }

        $ebak                      = $target[$this->weighField];
        $target[$this->weighField] = $row[$this->weighField];
        $row[$this->weighField]    = $ebak;
        $row->save();
        $target->save();

        $this->success();
    }

    /**
     * 加载为select(远程下拉选择框)数据，默认还是走$this->index()方法
     * 必要时请在对应控制器类中重写
     */
    public function select()
    {

    }

    /** 获取当前时间戳，精确到毫秒 */
    function microtime_float()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }



    /** 格式化时间戳，精确到毫秒，x代表毫秒 */

    function microtime_format($tag, $time)
    {
        list($usec, $sec) = explode(".", $time);
        $date = date($tag,$usec);
        return str_replace('x', $sec, $date);
    }
    //审批流

    /**
     * @param $bizno string 工作单编号
     * @param $department string 部门
     * @param $type string 流程类别
     * @param $price int 金额
     * @return int
     */

    public function createflowdata($bizno,$department,$type,$price){
        $adminInfo          = $this->auth->getInfo();
        //查出审批流
        $sql="select  dbo.f_getflowid("."'$type'".","."'$department'".","."'$price'".") as flowid";
        $sp=Db::query($sql)[0];
        if($sp['flowid']==0){
            $this->error('未设置审批流程，请联系管理员。');
        }elseif ($sp['flowid']==-1){
            $this->error('审批流程设置重复，请联系管理员');
        }else{
            //查询是否已发起审批流
            $flowstatus=$this->status($bizno);
            if($flowstatus=='未发起' ||$flowstatus=='已退回'){

                //添加审批数据
                $sql="SET NOCOUNT ON ; EXEC createflowdata '".$bizno."','".$adminInfo['id']."','".$adminInfo['nickname']."',".$sp['flowid'];
                $q=Db::query($sql);
                if($q){
                    return 200;
                }
            }else{
                return  201;
            }
        }
    }

    /**
     * @param $bizno
     * @return mixed
     * 查看审批状态
     */
    public function status($bizno){
        $sql="select  dbo.f_getflowstatus('".$bizno."') as status";
        return Db::query($sql)[0]['status'];
    }
    /**
     * @param $corp
     * @return mixed
     * 审批按钮是否有效
     * 1：可以提交，需要插入corpsq表   2：可以提交，corpsq表已有，不需再插入    0：不能提交
     */
    public function getcorpsq($corp){
        $sql="select  dbo.f_getcorpsq( '".$corp."') as status";
        $status=Db::query($sql);
        return $status[0]['status'];
    }

    /**
     * @param $type string 客户/供应商
     */
    public function getmaxno($type){
        $time=date('ym',time());
        $sql="SET NOCOUNT ON ; DECLARE @MAXNO VARCHAR(30) EXEC GETMAXNO '$type','$time',4,@MAXNO output select @MAXNO as no" ;
        return Db::query($sql)[0]['no'];
    }

    /**
     * @param string $hs 函数名
     * @param string $tzid
     * @return mixed
     */
    public function print_s($hs,$tzid){
        $sql="SET NOCOUNT ON ; DECLARE @MAXNO VARCHAR(30) EXEC $hs '$tzid'" ;
        return Db::query($sql);
    }

    /**
     * 获取表字段
     * @param $name
     * @return mixed
     */
    public function sqls($name){
        return Db::query("SELECT B.name AS name,C.value AS value FROM sys.tables A INNER JOIN sys.columns B ON B.object_id = A.object_id LEFT JOIN sys.extended_properties C ON C.major_id = B.object_id AND C.minor_id = B.column_id WHERE A.name = '$name'");
    }
    /**
     * array_filter_recursive 清除多维数组里面的空值
     * @param array $array
     * @return array
     */

   public function array_filter_recursive(array &$arr)
    {
        if (count($arr) < 1) {
            return [];
        }
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $arr[$k] =$this->array_filter_recursive($v);
            }
            if (is_null($arr[$k]) && $arr[$k] == '') {
                unset($arr[$k]);
            }
        }
        return array_filter($arr);
    }
    //处理读取decimal 类型数据
    public  function convert_number($number){

        return preg_replace('/^(\.\d+)/', '0$1', $number);

    }
}